package com.zdgk.core.control.forward.network;

import com.zdgk.core.control.config.ControlConfigInfo;
import com.zdgk.core.control.forward.network.listener.IEC104ServerEventListener;
import com.zdgk.core.web.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.openmuc.j60870.Server;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Slf4j
@Component
public class IEC104Config {

    @Resource
    IEC104ServerEventListener serverEventListener;
    @Resource
    private ConfigService configService;
    private ControlConfigInfo controlConfigInfo;

    private static Server server;

    @PostConstruct
    public void init() {
        try {
            if (isConnected()) {
                server.stop();
                server = null;
            }
            controlConfigInfo = configService.getControlKey();
            server = Server.builder().setPort(controlConfigInfo.getPort104()).build();
            server.start(serverEventListener);
            log.info("104从站服务启动成功[{}]", controlConfigInfo.getPort104());
        } catch (Exception e) {
            log.error("104从站服务启动失败[{}]", controlConfigInfo.getPort104());
        }
    }

    public boolean isConnected() {
        return server != null && !server.isStopped();
    }

}
